<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2019-04-09
 * Time: 17:25
 */

namespace app\api\controller;

use app\service\AddressService;
use app\service\CartService;
use app\service\GoodsService;
use app\service\LogService;
use app\service\OrdergoodsService;
use app\service\OrderService;
use app\common\model\Order as OrderModel;
use app\common\model\GoodsSku as GoodsSkuModel;
use think\Exception;
use app\common\model\UnionOrder;
use app\common\model\GoodsCard;
use app\common\model\User;
use app\service\MsgService;

class Order extends Base
{
    //新增订单
    public function add_order()
    {
        try {
            $input = input();
            $goods_id = $input['goods_id'];
            $goods_num = $input['goods_num'];
            $type = $input['type'];

            if ($input['sku_id']) {
                $sku = GoodsSkuModel::getOneById($input['sku_id']);
                $goods_info = GoodsService::S()->queryGoodsInfoByWhere(array('id' => $sku['goods_id']));
                $goods_info[0]['sku_id'] = $sku['id'];
                $goods_info[0]['sku_name'] = $sku['name'];
                $goods_info[0]['price'] = $sku['price'] ? $sku['price'] : $goods_info[0]['price'];
                $goods_id = $sku['goods_id'];
            } else {
                $goods_info = GoodsService::S()->queryGoodsInfoByWhere(array('id' => $goods_id));
            }
            $goods_info[0]['goods_num'] = $goods_num;
            if ($goods_info[0]['onsale'] == 0) {
                $this->ajax(202, '该商品已下架');
            }
            if ($goods_info[0]['stock'] < $goods_num) {
                $this->ajax(202, '库存不足');
            }
            $score = $this->member['score'];
            if($this->sid){
                $score = $this->student['score'];
            }
            if($type && ($score<$goods_info[0]['price']*$goods_num)){
                $this->ajax(202, '积分不足');
            }
            $goods_info[0]['type'] = $type;
            $address_id = input('post.address_id');//查询收货地址信息是否存在

            if (empty($address_id) && $goods_info[0]['shop_type'] != 4) {
                $this->ajax(202, '请填写收货地址信息');
            }
            $re = self::get_order($goods_info);
            echo json_encode($re);
            exit();
        } catch (Exception $ex) {
            LogService::S()->writeLog('Exception', $ex->getMessage());
            $this->ajax(202, $ex->getMessage());
        }
    }


    //购物车下单
    public function cart_order()
    {
        try {
            $cart_ids = input('post.cart_ids');
            $where['zkhb_cart.id'] = array('in', $cart_ids);
            $goods_info = CartService::S()->queryCartGoodsList($where);
            if (empty($goods_info)) {
                $this->ajax(202, '没有商品信息');
            }
            foreach ($goods_info as $k => $v) {
                if ($v['sku_id']) {
                    $sku = GoodsSkuModel::getOneById($v['sku_id']);
                    $goods_info[$k]['sku_id'] = $sku['id'];
                    $goods_info[$k]['sku_name'] = $sku['name'];
                    $goods_info[$k]['price'] = $sku['price'] ? $sku['price'] : $v['price'];
                }
            }
            $re = self::get_order($goods_info);
            if ($re['code'] == 200) {
                CartService::S()->delCart($cart_ids, $this->uid);
            }
            $address_id = input('post.address_id');//查询收货地址信息是否存在
            if (empty($address_id)) {
                $this->ajax(202, '请填写收货地址信息');
            }
            echo json_encode($re);
            exit();
        } catch (Exception $ex) {
            LogService::S()->writeLog('Exception', $ex->getMessage());
            $this->ajax(202, $ex->getMessage());
        }

    }


    //获取订单信息
    protected function get_order($goods_info, $identity = 1)
    {
        try {
            $input = input();
            if (empty($goods_info)) {
                $this->ajax(202, "没有商品信息哦");
            }
            $shop_type = 1;
            foreach ($goods_info as $k => $v) {
                if ($goods_info[$k]['onsale'] == 0) {
                    $this->ajax(202, "{$v['name']}-商品已下架");
                }
                if ($goods_info[$k]['stock'] < $v['goods_num']) {
                    $this->ajax(202, "{$v['name']}-库存不足");
                }
                $shop_type = $v['shop_type'];
            }
            if ($shop_type == 4) {
                //购买等级是店长
                if ($goods_info[0]['grade'] == 4 && in_array($this->member['grade_id'], array(2, 3))) {//
                    //&&($goods_info[0]['grade'])<=$this->member['grade_id']
                    $this->ajax(202, "您已经购买该等级");
                } else {
                    if ($goods_info[0]['grade'] <= $this->member['grade_id']) {
                        $this->ajax(202, "您已经购买该等级");
                    }
                }

            }
            if ($shop_type == 1) {
                if (!$input['fenyong_type']) {
                    //$this->ajax(202,"请选择优惠类型");
                }
            }
            $address_id = input('post.address_id');//查询收货地址信息是否存在
            $address_info = array();
            if (!empty($address_id)) {
//                $address_info = AddressService::S()->findAddress(array('id' => $address_id, 'uid' => $this->uid));
                $address_info = AddressService::S()->findAddress(array('id' => $address_id));
                if (!$address_info) {
                    $this->ajax(202, '收货地址不存在');
                }
            }


            $make_order = self::make_order($goods_info, $address_info);

            /*//拼单逻辑 取消拼单逻辑
            if(($shop_type==1)&&$input['main_order_id']) {
                $canPin = OrderService::S()->checkMainOrder($this->uid,$input['main_order_id']);
                if($canPin!==true) {
                    $this->ajax(202,$canPin);
                }
                $make_order['main_order_id'] = $input['main_order_id'];
            }*/
            if ($shop_type == 1) {
                $referOrder = OrderModel::getOne([
                    'uid' => $this->member['refer_id'],
                    'is_end' => 0,
                    'checked' => [
                        'in', [1, 2, 5]
                    ],
                    'shop_type' => 1,
                    'fenyong_type' => 2
                ]);
                if ($referOrder) {
                    $make_order['main_order_id'] = $referOrder['id'];
                }
            }

            /*  $referOrder = OrderModel::getOne([
                 'uid' => $this->member['refer_id'],
                 'is_end' => 0,
                 'checked' => [
                     'in',[1,2,5]
                 ],
                 'shop_type' => 1
             ]);
             if($referOrder) {
                 $make_order['main_order_id'] = $referOrder['id'];
             } */

            $make_order['fenyong_type'] = $input['fenyong_type'];//1返还积分 2拼三免一
            $make_order['shop_type'] = $shop_type;
            $make_order['remark'] = $input['remark'];
            $make_order['delivery_name'] = $address_info['name'];
            $make_order['identity'] = $identity;
            $make_order['delivery_mobile'] = $address_info['mobile'];
            $make_order['delivery_province'] = $address_info['province'];
            $make_order['delivery_city'] = $address_info['city'];
            $make_order['delivery_county'] = $address_info['county'];
            $make_order['delivery_address'] = $address_info['address'];
            $make_order['uid'] = $this->uid;
            $make_order['goods_list'] = json_encode($goods_info);
            $make_order['create_time'] = time();
            $make_order['title'] = $goods_info[0]['name'];//订单标题
            $make_order['sid'] = $this->sid;//学员ID
            $order_id = OrderService::S()->addOrder($make_order);

            if ($order_id) {
                //本人主订单
                if (($shop_type == 1) && !$input['main_order_id']) {
                    //OrderModel::where('id',$order_id)->update(['main_order_id'=>$order_id]);
                }
                //添加订单商品信息
                $addGoodsInfo = array();
                foreach ($goods_info as $k => $v) {
                    $addGoodsInfo[] = array(
                        'goods_id' => $v['id'],
                        'goods_num' => $v['goods_num'],
                        'order_id' => $order_id
                    );
                }
                $re = OrdergoodsService::S()->addOrderGoods($addGoodsInfo); //创建订单
                //扣除用户使用货币
                $make_order['id'] = $order_id;
                if ($re) {
                    return $this->back_array(200, "订单已提交,正在转入支付页面...", array('is_pay' => 0, 'order_id' => $order_id)); //订单未支付成功 需要用第三发支付
                } else {
                    return $this->back_array(202, "下单失败......", array('is_pay' => 0, 'order_id' => $order_id)); //订单未支付成功 需要用第三发支付
                }
            } else {
                return $this->back_array(202, "创建订单失败", array('is_pay' => 0)); //订单未支付成功 需要用第三发支付
            }
        } catch (Exception $ex) {
            LogService::S()->writeLog('Exception', $ex->getMessage());
            return $this->back_array(202, $ex->getMessage());
        }
    }



    /**
     * 返回用户数据
     * @param $code
     * @param $msg
     * @param $data
     * @return array
     */
    protected function back_array($code, $msg, $data)
    {
        return array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        );
    }

    //取消订单
    public function cancel_order()
    {
        $order_id = input('post.order_id');
        $order_info = OrderService::S()->findOrder(array('id' => $order_id));
        if ($order_info['checked'] == 6) { //订单是已支付，已完成,已发货 不能取消
            $this->ajax(202, '订单已取消');
        }
        if ($order_info['checked'] != 0) {
            $this->ajax(202, '订单状态不能取消');
        }
        $save = array('checked' => 6);
        $save['close_time'] = time();//date('Y-m-d H:i:s');
        $save['close_reason'] = input('post.close_reason');
        $re = OrderService::S()->saveOrder($save, array('id' => $order_id));
        if ($re) {
            //资金返还 TODO
            $this->ajax(200, '取消成功');
        }
    }

    /**创建订单数据
     * @param $goods_info
     * @param $address_info
     * @return mixed
     */
    protected function make_order($goods_info, $address_info)
    {
        $data['uid'] = $this->uid;
        $data['mall_id'] = $this->mall_id;
        //$data['create_time']=date('Y-m-d H:i:s');
        $data['order_sn'] = create_order_sn($this->uid);
        $data['express_money'] = AddressService::S()->_get_shipping($goods_info, $address_info['province']);//self::get_shipping($goods_info,$delivery_data['province_id']);
        $shipping = $data['express_money'];
        $goods_money = 0;
        $pin_money = 0;
        foreach ($goods_info as $k => $v) {
            if($goods_info[0]['type']==0) {
                  $v['price'] = $v['score_price'];
            }
            $goods_money += $v['price'] * $v['goods_num'];
            if ($v['is_pin']) {
                $pin_money += $v['price'] * $v['goods_num'];
            }
        }
        $data['goods_list'] = json_encode($goods_info);
        $data['goods_money'] = $goods_money;
        $data['pin_money'] = $pin_money;
        $data['all_money'] = $goods_money + $data['express_money'];
        $data['type'] = $goods_info[0]['type'];
        $data['pay_money'] = $goods_money + $shipping;//总的费用=优惠后的商品钱+运费
        $data['pay_money'] = round($data['pay_money'], 2);//四舍五入
        if ($data['pay_money'] < 0) {
            $this->ajax(202, "商品价格出错了");//可以等于0
        }
        $data['order_ip'] = \EasyWeChat\Kernel\Support\get_client_ip();//订单ip
        return $data;
    }

    //查询订单列表
    public function order_list()
    {
        $where['uid'] = $this->uid;
        $checked = input('post.checked');
        $input = input();
        $where['shop_type'] = $input['shop_type'] ? $input['shop_type'] : 1;
        if ($where['shop_type'] == 1) {
            $where['shop_type'] = [
                'in', [
                    1, 4, 5
                ]
            ];
        }
        if (!$checked) {
            if (strlen($checked) == 1) {
                $where['checked'] = 0;//$checked;
            }
        } else {
            if ($checked != 'all') { //查看所有订单
                $where['checked'] = $checked;
            }
        }
        //dump($where);die;
        $page = defaultPage();
        $page_num = 20;
        $filed = 'id,create_time,checked,title,order_sn,all_money,goods_money,pay_money,express_money,goods_list,main_order_id,shop_type';
        $orderInfo = OrderService::S()->selectOrder($where, $page, $page_num, $filed);
        foreach ($orderInfo as $k => $v) {
            $goods_list = @GoodsService::S()->dealGoods(json_decode($v['goods_list'], true));//;//OrdergoodsService::S()->selectGoods(array('order_id'=>$v['id']));
            $new_goods_list = array();
            foreach ($goods_list as $gk => $gv) { //处理商品
                $new_goods_list[$gk]['goods_id'] = $gv['id'];
                $new_goods_list[$gk]['goods_name'] = $gv['name'];
                $new_goods_list[$gk]['price'] = $gv['price'];
                $new_goods_list[$gk]['shop_price'] = $gv['shop_price'];
                $new_goods_list[$gk]['goods_num'] = $gv['goods_num'];
                $new_goods_list[$gk]['picture'] = $gv['picture'];
                $new_goods_list[$gk]['guige'] = $gv['guige'];
                $new_goods_list[$gk]['sku_name'] = $gv['sku_name'];
            }
            $orderInfo[$k]['goods_list'] = $new_goods_list;
            $orderInfo[$k]['count_nums'] = count($new_goods_list);
            $orderInfo[$k]['pintuanInfo'] = OrderService::S()->pintuanInfo($v['id']);
        }
        $pagecount = ceil(OrderService::S()->countOrder($where) / $page_num);
        $data['order_list'] = $orderInfo;
        $data['page_count'] = $pagecount;
        $this->ajax(200, 'success', $data);
    }

    //订单详细信息查询
    public function order_detail()
    {
        $order_id = input('post.order_id');
        if (!$order_id) {
            $this->ajax(202, 'error');
        }
        $filed = 'id,create_time,checked,title,order_sn,all_money,goods_money,pay_money,express_money,goods_list,
        delivery_name,delivery_mobile,delivery_province,delivery_city,delivery_county,delivery_address,remark,main_order_id,shop_type,is_end,
        yongjin_money,score_money,cash_money,sid';
        $orderInfo = OrderService::S()->findOrder(array('id' => $order_id, 'uid' => $this->uid), $filed);
        if (!$orderInfo) {
            $this->ajax(202, 'error');
        }
        $goods_list = GoodsService::S()->dealGoods(json_decode($orderInfo['goods_list'], true));//;//OrdergoodsService::S()->selectGoods(array('order_id'=>$v['id']));
        $new_goods_list = array();
        foreach ($goods_list as $gk => $gv) { //处理商品
            $new_goods_list[$gk]['goods_id'] = $gv['id'];
            $new_goods_list[$gk]['goods_name'] = $gv['name'];
            $new_goods_list[$gk]['price'] = $gv['price'];
            $new_goods_list[$gk]['shop_price'] = $gv['shop_price'];
            $new_goods_list[$gk]['goods_num'] = $gv['goods_num'];
            $new_goods_list[$gk]['picture'] = $gv['picture'];
            $new_goods_list[$gk]['sku_name'] = $gv['sku_name'];
            $new_goods_list[$gk]['type'] = $gv['type'];
        }
        $orderInfo['goods_list'] = $new_goods_list;
        $orderInfo['pintuanInfo'] = OrderService::S()->pintuanInfo($orderInfo['id']);
        //最大积分使用额度
        $max = 0;
        if ($orderInfo['shop_type'] == 2) {
            foreach ($goods_list as $v) {
                $max += $v['price'] * $v['score_bili'] * $v['goods_num'];
            }
        }
        $orderInfo['max_score'] = round($max, 2);

        $orderInfo['student'] = \app\common\model\Student::getOne(['id'=>$orderInfo['sid']]);

        $this->ajax(200, 'success', $orderInfo);

    }

    /* 运费 */
    public function shipping()
    {
        $goods_id = input('post.goods_id');
        $address_id = input('post.address_id');//查询收货地址信息是否存在
        if (empty($address_id)) {
            $this->ajax(202, '请填写收货地址信息');
        }
        $address_info = AddressService::S()->findAddress(array('id' => $address_id, 'uid' => $this->uid));
        if (!$address_info) {
            $this->ajax(202, '收货地址不存在');
        }
        if ($goods_id) {
            $goods_num = input('post.goods_num');
            $goods_info = GoodsService::S()->queryGoodsInfoByWhere(array('id' => $goods_id));
            $goods_info[0]['goods_num'] = $goods_num;
        } else {
            $cart_ids = input('post.cart_ids');
            $where['zkhb_cart.id'] = array('in', $cart_ids);
            $goods_info = CartService::S()->queryCartGoodsList($where);
        }
        if (empty($goods_info)) {
            $this->ajax(202, '没有商品信息');
        }
        $shipping = AddressService::S()->_get_shipping($goods_info, $address_info['province']);
        if ($shipping === false) {
            $this->ajax(202, '参数错误');
        }
        $this->ajax(200, 'success', $shipping);
    }

    /* 检查是否可以参与该拼团 */
    public function checkMainOrder()
    {
        $input = input();
        $this->ajax(200, '');
        if (!$input['main_order_id']) {
            $this->ajax(202, '参数错误');
        }
        $res = OrderService::S()->checkMainOrder($this->uid, $input['main_order_id']);
        if ($res === true) {
            $list = OrderService::S()->pintuanInfo($input['main_order_id']);
            $this->ajax(200, 'success', $list);
        }
        $this->ajax(202, $res);
    }

    /* 订单物流信息 */
    public function wuliu()
    {
        $input = input();
        $order = OrderModel::getOne(['id' => $input['id']]);
        if (!$order) {
            $this->ajax(202, '订单不存在');
        }
        if (!$order['express_no'] || !$order['express_com']) {
            $this->ajax(202, '无物流信息');
        }
        $res = OrderService::S()->getWuliu($order['express_no'], $order['express_com']);
        if ($res) {
            $this->ajax(200, $res);
        }
        $this->ajax(202, '无物流信息');
    }

    /* 用户确认收货 */
    public function shouhuo()
    {
        $input = input();
        $order = OrderModel::getOne(['id' => $input['id']]);
        if (!$order) {
            $this->ajax(202, '订单不存在');
        }
        if ($order['checked'] != 5) {
            $this->ajax(202, '该订单无法确认收货');
        }
        OrderModel::where([
            'id' => $order['id']
        ])->update([
            'shouhuo_time' => time(),
            'checked' => 2
        ]);
        $this->ajax(200, '已确认收货');
    }

    /* 淘客订单列表 */
    public function taokeList()
    {
        $input = input();
        $page = max($input['page'], 1);
        $size = 20;
        $where = [
            'union_uid' => $this->uid,
            'type' => 'jd'
        ];
        $list = UnionOrder::getPage($where, $page, $size, 'id desc');
        if (!$list) {
            $this->ajax(200, '', []);
        }
        foreach ($list as $k => $v) {
            $list[$k]['content'] = json_decode($v['content'], true);
            $list[$k]['status_text'] = UnionOrder::getOrderStatusText($v['status']);
        }
        $this->ajax(200, 'success', $list);
    }


    /* 拼多多订单列表 */
    public function PddList()
    {
        $input = input();
        $page = max($input['page'], 1);
        $size = 20;
        $where = [
            'union_uid' => $this->uid,
            'type' => 'pdd'
        ];
        $list = UnionOrder::getPage($where, $page, $size, 'id desc');
        if (!$list) {
            $this->ajax(200, '', []);
        }
        foreach ($list as $k => $v) {
            $list[$k]['content'] = json_decode($v['content'], true);
            $list[$k]['status_text'] = UnionOrder::getOrderPddStatusText($v['status']);
        }
        $this->ajax(200, 'success', $list);
    }

    /* 提货 */
    public function tihuo()
    {
        $input = input();
        if (!$input['number']) {
            $this->ajax(202, '请输入卡号');
        }
        if (!$input['password']) {
            $this->ajax(202, '请输入密码');
        }
        $card = GoodsCard::getOne([
            'number' => $input['number'],
            'password' => $input['password']
        ]);
        if (!$card) {
            $this->ajax(202, '卡券无效');
        }
        //只是检查卡券是否有效，并不是提货
        if ($input['check']) {
            $this->ajax(200, '卡券有效', $card);
        }
        if (!$input['name']) {
            $this->ajax(202, '请输入姓名');
        }
        if (!$input['mobile']) {
            $this->ajax(202, '请输入手机号');
        }
        if (!$input['province']) {
            $this->ajax(202, '请选择省');
        }
        if (!$input['city']) {
            $this->ajax(202, '请选择市');
        }
        if (!$input['county']) {
            $this->ajax(202, '请选择区/县');
        }
        if (!$input['address']) {
            $this->ajax(202, '请填写详细地址');
        }
        $goodsList[] = [
            'name' => $card['name'],
            'price' => 0,
            'goods_num' => 1
        ];
        $orderInfo = [
            'mall_id' => $this->member['mall_id'],
            'uid' => $this->uid,
            'title' => $card['name'],
            'order_sn' => create_order_sn($this->uid),
            'checked' => 1,
            'pay_time' => time(),
            'delivery_name' => $input['name'],
            'delivery_mobile' => $input['mobile'],
            'delivery_province' => $input['province'],
            'delivery_city' => $input['city'],
            'delivery_county' => $input['county'],
            'delivery_address' => $input['address'],
            'shop_type' => 5,
            'goods_list' => json_encode($goodsList)
        ];
        $res = OrderModel::create($orderInfo);
        if ($res->id) {
            GoodsCard::where([
                'id' => $card['id']
            ])->update([
                'status' => 1,
                'use_time' => time(),
                'uid' => $this->uid,
                'order_id' => $res->id
            ]);
            //赠送积分 
            if ($card['score'] > 0) {
                $orderInfo = OrderModel::getOneById($res->id);
                User::changeMoney($this->uid, 2, $card['score'], $content = '提货赠送积分', $orderInfo, $other = false);
            }
            //绑定上级
            if (!$this->member['refer_id'] && $card['sale_uid']) {
                $userInfo = $this->member;
                $referInfo = User::getOne(['id' => $card['sale_uid']]);
                $refer_id = $card['sale_uid'];
                if (User::checkRefer($this->uid, $refer_id)) {
                    $res = User::where(['id' => $this->uid])->update([
                        'refer_id' => $refer_id
                    ]);
                    if ($res) {
                        MsgService::S(['mall_id' => $referInfo['mall_id']])->sendTemp('NEW_USER', $referInfo['mall_id'], $referInfo['id'], [
                            'first' => '有新用户加入',
                            'nickname' => $userInfo['nickname'],
                            'remark' => ''
                        ]);
                    }
                }

            }
            $this->ajax(200, '提货成功');
        } else {
            $this->ajax(202, '创建订单失败');
        }
    }

}